﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Newtonsoft.Json;
using System.Security.Cryptography;

namespace JwT
{
    public class TokenHelper : ITokenHelper
    {
        private readonly JwtTokenOption _options;

        public TokenHelper(JwtTokenOption options)
        {
            _options = options;
        }

        public TnToken CreateToken<T>(T entity) where T : class
        {
            List<Claim> claims = new List<Claim>();
            foreach (var item in entity.GetType().GetProperties())
            {
                object obj = item.GetValue(entity);
                string value = "";
                if (obj != null)
                {
                    value = obj.ToString();
                }
                claims.Add(new Claim(item.Name, value));
            }
            return CreateTokenString(claims);
        }

        public TnToken CreateToken(Dictionary<string, string> keyValuePairs)
        {
            List<Claim> claims = new List<Claim>();
            foreach (var item in keyValuePairs) 
            { 
                claims.Add(new Claim(item.Key, item.Value)); 
            }
            return CreateTokenString(claims);
        }

        private TnToken CreateTokenString(List<Claim> claims)
        {
            DateTime expires =
            DateTime.Now.AddMinutes(_options.AccessTokenExpiresMinutes);
            var token = new JwtSecurityToken(
                issuer: _options.Issuer,
                audience: _options.Audience,
                claims: claims, //携带的荷载
                notBefore: DateTime.Now, //token生成时间
                expires: expires, //token过期时间
                signingCredentials: new SigningCredentials(
                new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.IssuerSigningKey)),
                SecurityAlgorithms.HmacSha256
                )
                );
            return new TnToken 
            { 
                Expires = expires, TokenStr = new JwtSecurityTokenHandler().WriteToken(token) 
            };
        }
    }
}
